package com.itheima.stock.config;


import com.itheima.stock.pojo.vo.TaskThreadPoolInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;


import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 构建线程池
 */
@Configuration
public class TaskExecutePoolConfig {
    @Autowired
    private TaskThreadPoolInfo info;

    // destroyMethod = "shutdown" shudown方法来自ThreadPoolTaskExecutor()内部，作用只有旧的任务结束之后新的任务才能提交
    //initMethod = 这把bean被初始化完成后毁掉的方法
    @Bean(name = "threadPoolTaskExecutor",destroyMethod = "shutdown"  )
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数
        threadPoolTaskExecutor.setCorePoolSize(info.getCorePoolSize());
        //最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(info.getMaxPoolSize());
        //线程最大存活时间
        threadPoolTaskExecutor.setKeepAliveSeconds(info.getKeepAliveSeconds());
        //任务队列
        threadPoolTaskExecutor.setQueueCapacity(info.getQueueCapacity());
        //拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        //将设置的参数初始化
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}
